﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.AspNet.SignalR;

namespace ERPStore.Web.NewsLetters.EventConsumers
{
	public class NewsLetterSignalTrackEventConsumer : EventBrokR.IConsumer<ERPStore.NewsLetters.Events.SignalNewsLetterTrackEvent>
	{
		public NewsLetterSignalTrackEventConsumer(ERPStore.NewsLetters.Services.NewsLettersService newsLettersService)
		{
			this.NewsLettersService = newsLettersService;
		}

		protected ERPStore.NewsLetters.Services.NewsLettersService NewsLettersService { get; private set; }

		#region IConsumer<NewsLetterTrackEvent> Members

		public void Handle(ERPStore.NewsLetters.Events.SignalNewsLetterTrackEvent eventMessage)
		{
			var emailSent = new ERPStore.NewsLetters.Models.EmailSentResult();
			if (eventMessage.EmailSentId.HasValue)
			{
				emailSent = NewsLettersService.GetEmailSentById(eventMessage.EmailSentId.Value);
			}

			var track = new ERPStore.NewsLetters.Models.Track();
			track.CreationDate = eventMessage.CreationDate;
			track.EventDate = DateTime.Now;
			track.CampaingId = eventMessage.Track.CampaignId;
			track.Email = eventMessage.Track.Email;
			track.LinkName = eventMessage.Track.LinkName;
			track.NewsLetterId = eventMessage.Track.NewsLetterId;
			track.UserId = eventMessage.Track.UserId;
			track.Ip = eventMessage.Ip;
			track.Url = eventMessage.RawUrl;
			track.EmailSent = emailSent;
			track.DestinationUrl = eventMessage.DestinationUrl;

			var jsonSerializer = new Newtonsoft.Json.JsonSerializer();
			var sb = new StringBuilder();
			var textWriter = new System.IO.StringWriter(sb);
			var jsonWriter = new Newtonsoft.Json.JsonTextWriter(textWriter);
			jsonSerializer.Serialize(jsonWriter, track);

			var cnx = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetConnectionContext<NewsLetterConnection>();
			cnx.Connection.Broadcast(sb.ToString());
		}

		#endregion
	}
}
